package com.zhiwei.msf.gateway.service.impl;

import java.util.Collections;
import java.util.List;

import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;
import com.zhiwei.msf.common.config.SecurityContext;
import com.zhiwei.msf.common.dto.PageDataDto;
import com.zhiwei.msf.common.exception.BasePublishException;
import com.zhiwei.msf.common.util.SqlUtil;
import com.zhiwei.msf.gateway.constants.GatewayConstant;
import com.zhiwei.msf.gateway.constants.GatewayErrorConstants;
import com.zhiwei.msf.gateway.dao.entity.UserInfo;
import com.zhiwei.msf.gateway.dao.entity.UserInfoExample;
import com.zhiwei.msf.gateway.dao.mapper.UserInfoMapper;
import com.zhiwei.msf.gateway.dao.mapper.extmapper.ExtUserInfoMapper;
import com.zhiwei.msf.gateway.dto.QueryUserInfoDto;
import com.zhiwei.msf.gateway.service.UserInfoService;

import lombok.extern.slf4j.Slf4j;

/**
 * function: 用户服务(注册、删除、token用户服务)
 * author: zhiwei_yang
 * time: 2020/2/12-15:53
 */
@Slf4j
@Service
public class UserInfoServiceImpl implements UserInfoService {

    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private ExtUserInfoMapper extUserInfoMapper;

    @Override
    public UserInfo getDefaultUserInfo() {
        UserInfo userInfo = new UserInfo();
        userInfo.setUsername(GatewayConstant.ROUTE_USER_NAME);
        userInfo.setPassword(GatewayConstant.ROUTE_USER_PASSWORD);
        return userInfo;
    }

    @Override
    public UserInfo getUserInfoByName(String username) {
        if (StringUtils.isEmpty(username)) {
            return null;
        }
        UserInfoExample userInfoExample = new UserInfoExample();
        UserInfoExample.Criteria criteria = userInfoExample.createCriteria();
        criteria.andUsernameEqualTo(username);
        List<UserInfo> userInfoList = userInfoMapper.selectByExample(userInfoExample);
        log.info("查询用户信息username:[{}], userInfo ==> {}", username, userInfoList);
        return CollectionUtils.isEmpty(userInfoList) ? null : userInfoList.get(0);
    }

    @Override
    public boolean addUser(UserInfo userInfo) {
        log.info("新增用户userInfo:{}", userInfo);
        return userInfoMapper.insert(userInfo) == 1;
    }

    /**
     * 更新用户
     *
     * @param userInfo 用户信息
     * @return
     */
    public boolean updateUser(UserInfo userInfo) {
        log.info("待更新用户信息userInfo:{}", JSON.toJSONString(userInfo));
        if (StringUtils.isEmpty(userInfo.getUuid())) {
            throw new BasePublishException(GatewayErrorConstants.USER_ID_INVALID);
        }
        return userInfoMapper.updateByPrimaryKeySelective(userInfo) == 1;
    }

    @Override
    public boolean deleteUser(String userId) {
        if (StringUtils.isEmpty(userId)) {
            throw new BasePublishException(GatewayErrorConstants.USER_ID_INVALID);
        }
        int count = userInfoMapper.deleteByPrimaryKey(userId);
        log.info("删除用户[{}],result:{}", userId, count == 1);
        if (count == 0) {
            throw new BasePublishException(GatewayErrorConstants.USER_NOT_EXIST);
        }
        return count == 1;
    }

    @Override
    public PageDataDto<UserInfo> search(QueryUserInfoDto queryUserInfoDto) {
        PageDataDto<UserInfo> userInfoPageDataDto = new PageDataDto<>();
        userInfoPageDataDto.setPageNow(queryUserInfoDto.getPageNow());

        UserInfoExample userInfoExample = new UserInfoExample();
        UserInfoExample.Criteria criteria = userInfoExample.createCriteria();
        criteria.andUsernameNotEqualTo(SecurityContext.getUsername());
        if (!StringUtils.isEmpty(queryUserInfoDto.getUuid())) {
            criteria.andUuidEqualTo(queryUserInfoDto.getUuid());
        }
        if (!StringUtils.isEmpty(queryUserInfoDto.getUsername())) {
            criteria.andUsernameLike(SqlUtil.getLikeSplit(queryUserInfoDto.getUsername()));
        }
        if (!StringUtils.isEmpty(queryUserInfoDto.getPhone())) {
            criteria.andPhoneLike(SqlUtil.getLikeSplit(queryUserInfoDto.getPhone()));
        }
        if (!StringUtils.isEmpty(queryUserInfoDto.getEmail())) {
            criteria.andEmailLike(SqlUtil.getLikeSplit(queryUserInfoDto.getEmail()));
        }
        int count = userInfoMapper.countByExample(userInfoExample);
        userInfoPageDataDto.setRowCount(count);
        userInfoPageDataDto.setPageCount(count % queryUserInfoDto.getPageSize() == 0 ?
                count / queryUserInfoDto.getPageSize() :
                count / queryUserInfoDto.getPageSize() + 1);
        if (count == 0) {
            userInfoPageDataDto.setData(Collections.emptyList());
            log.info("用户信息查询为空queryUserInfoDto：{}", JSON.toJSONString(queryUserInfoDto));
            return userInfoPageDataDto;
        }

        //分页查询
        RowBounds rowBounds = new RowBounds((queryUserInfoDto.getPageNow() - 1) * queryUserInfoDto.getPageSize(),
                queryUserInfoDto.getPageSize());
        List<UserInfo> userInfoList = extUserInfoMapper.selectByExample(userInfoExample, rowBounds);
        userInfoPageDataDto.setData(userInfoList);
        log.info("用户信息查询queryUserInfoDto:{},响应:{}", JSON.toJSONString(queryUserInfoDto), JSON.toJSONString(userInfoList));
        return userInfoPageDataDto;
    }
}